自定义滑块Range Slider

自定义滑块Range Slider

原生的组件虽然长得丑,但是提供给我们的能力是很多的。原生的事件以及属性,这些是某些UI框架不能给我们的。所以,基于原生的一些组件来做一些定制化修改是有必要的。首先,我们来看一个常用的滑块组件。

场景

我在一个视频类demo中,使用到了滑块组件(也就是range类型的input组件)。

1
<input type="range" value="{{currentTime}}" min="0" max="{{duration}}" step="1" (input)="progressChange($event)">

未做定制的效果如下:
视频进度条和音量条

用到input的有两处,一个是视频的进度条,一个是音量条。不能说这个样式很丑,但是还有美化的空间。那么我们如何来修改input默认的样式呢?

自定义样式

input组件主要由两部分组成,轨道和滑块,它们都是伪元素。我们只要针对这两个伪元素来做试探性修改css就可以看到效果了。

1
2
3
4
5
6
7
8
9
// 轨道的伪元素,分别对应chrome,firefox,IE浏览器。
// ::-webkit-slider-runnable-track
// ::-moz-range-track
// ::-ms-track

// 滑块的伪元素,分别对应chrome,firefox,IE浏览器。
// ::-webkit-slider-thumb
// ::-moz-range-thumb
// ::-ms-thumb

去除浏览器的默认样式

每个浏览器对range类的input有不一样的默认样式,我们首先来去掉这种默认样式。

1
2
3
4
5
6
7
8
9
10
11
input[type=range] {
// 去除浏览器默认的样式
-webkit-appearance: none;
-moz-appearance: none;
width: 300px;
border-radius: 10px;
&:focus {
// 去除落焦时的外边框效果
outline: none;
}
}

修改轨道css

样式的修改方式如下所示,这里只给出chrome的修改内容给大家参考,具体想要的样式效果当然由自己而定。

1
2
3
4
5
input[type=range]::-webkit-slider-runnable-track {
height: 6px;
border-radius: 10px; /*将轨道设为圆角的*/
background: #ee2828;
}

修改滑块css

废话不多说,上代码。

1
2
3
4
5
6
7
8
9
10
input[type=range]::-webkit-slider-thumb {
-webkit-appearance: none;
-moz-appearance: none;
width: 10px;
height: 10px;
border-radius: 50%;
position: relative;
top: -2px;
background: #fff;
}

修改完毕,我们来看一下效果图。感觉还不错吧,加以修改,相信能做出更美的效果。
修改后效果图

放一个demo链接,大家自行查阅。


扫一扫下方小程序码或搜索Tusi博客,即刻阅读最新文章!

Tusi博客

You forgot to set the qrcode for Alipay. Please set it in _config.yml.
You forgot to set the qrcode for Wechat. Please set it in _config.yml.
You forgot to set the business and currency_code for Paypal. Please set it in _config.yml.
You forgot to set the url Patreon. Please set it in _config.yml.
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×